import java.util.ArrayList;
import java.util.List;

public class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode(int x) { val = x; }
 }

class Solution {
    //解法1 二叉搜索树的中序遍历则为有序
    public int kthLargest(TreeNode root, int k) {
        List<Integer> list = new ArrayList<>();
        helper(root, list);
        return list.get(k-1);
    }

    private void helper(TreeNode root, List<Integer> list) {
        if (root == null) return;
        if (root.right != null) helper(root.right, list);
        list.add(root.val);
        if (root.left != null) helper(root.left, list);
    }
    // 解法2 解法1的优化~
    int res, n;
    public int kthLargest2(TreeNode root, int k) {
        n = k;
        dfs(root);
        return res;
    }
    void dfs(TreeNode root) {
        if(root == null) return;
        if(n == 0) return;
        dfs(root.right);
        //if(n == 0) return;
        if(--n == 0) res = root.val;
        dfs(root.left);
    }

}